/*
 * =====================================================================================
 *
 *       Filename:  shadow_getspnam.c
 *
 *    Description:  =
 *
 *        Version:  1.0
 *        Created:  2019年07月15日 14时33分20秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */

#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <shadow.h>

void get_shadow_salt(const char *shadow, char *salt, size_t len)
{
    int i = 0;
    int j = 0;
    for(i = 0; i < strlen(shadow); i++) {
        if(shadow[i] == '$') {
            j++;
        }
        if(j >= 3) {
            break;
        }
        salt[i] = shadow[i];
    }
}

int main(int argc, char **argv)
{
    if(argc != 3) {
        printf("%s: username passwd\n", argv[0]);
        return 0;
    }
    struct spwd *gs = getspnam(argv[1]);
    if(NULL == gs) {
        perror("getspnam()");
        return 0;
    }
    printf("%s\n", gs->sp_pwdp);
    char salt[128] = {0};
    get_shadow_salt(gs->sp_pwdp, salt, sizeof(salt) - 1);
    printf("salt=%s\n", salt);
    if(salt[0]) {
        char *passwd = crypt(argv[2], salt);
        if(0 == strcmp(passwd, gs->sp_pwdp)) {
            printf("Password: %s for Username: %s is Right\n", argv[2], argv[1]);
        }
        else {
            printf("Password: %s for Username: %s is Wrong\n", argv[2], argv[1]);
        }
    }
    
    return 0;
}


